#!/bin/bash

if [ ${UID} -ne 0 ] ; then
	echo "Error, run again as root." 1>&2
	exit 1
fi

if [ ! -f ./rootfs.ext2 ] ; then
	echo "Error, rootfs.ext2 not found in current directory." 1>&2
	exit 2
fi

if [ ! -d "./mount_dir" ] ; then
	mkdir ./mount_dir || exit 3
fi

mountpoint -q ./mount_dir
if [ $? -ne 0 ] ; then
	mount '-orw,loop' -t ext4 ./rootfs.ext2 ./mount_dir
	if [ $? -ne 0 ] ; then
		echo "Error, failed to mount rootfs.ext2" 1>&2
		exit 4
	fi
fi

copycnt=0
while [ -n "$1" ] ; do
	if [ -e "$1" ] ; then
		cp -v -f -r --preserve=mode -P "$1" ./mount_dir/root/
		copycnt=$((copycnt + 1))
	else
		echo "target file or directory not found: $1" 1>&2
	fi
	shift 1
done

if [ ${copycnt} -eq 0 ] ; then
	echo "INFO: not umount rootfs.ext2"
else
	umount ./mount_dir
	echo "INFO: rootfs.ext2 => mount_dir umounted"
fi
exit 0
